package gbench.sandbox.matrix.blas;

import gbench.commonApp.data.DataMatrixApp;
import static gbench.common.tree.LittleTree.*;
import java.util.Arrays;
import java.util.stream.Collectors;
import static gbench.common.fs.XlsFile.*;
import org.jblas.DoubleMatrix;
import org.jblas.Solve;
import org.junit.jupiter.api.Test;

public class JunitBlas extends DataMatrixApp {
    
    public static DataMatrix<Double> M(DoubleMatrix mx){
        var builder = DMB(Double.class,mx.rows,mx.columns);
        return builder.get(mx.elementsAsList().toArray(Double[]::new));
    }
    
    /**
     * 把DataMatrix转乘DoubleMatrix
     * @param mx dataMatrix
     * @return DoubleMatrix
     */
    public static DoubleMatrix M(DataMatrix<Double> mx){
        return new DoubleMatrix(mx.height(),mx.width(),D2ds(mx.getFlatCells2()));
    }
    
    @Test()
    public void foo() {
        int n = 1000;
        var builder = DMB(Double.class,n,n);
        var dbls = DBLS(n*n);
        var dd = D2ds(dbls);
        println(dd.length);
        var dm = new DoubleMatrix(n,n,dd);
        dm = dm.mmul(dm);
        println(M(dm).toString(frt(2)));
        var m1 = builder.get(dbls);
        println(m1.mmult(m1).toString(frt(2)));
    }
    
    @Test()
    public void foo2() {
        int n = 1000;
        var dbls = DBLS(n);
        var builder = DSQB(10);
        println(builder.get(dbls).toString(frt(2)));
    }
    
    @Test()
    public void foo3() {
        int n =9;
        var builder = DMB(Double.class,n,n);
        var mm = builder.get(DBLSTREAM(100).map(e->(Number)(e*100d)).toArray(Double[]::new));
        println(mm);
        var m2 = M(mm);
        var p = Solve.pinv(m2);
        println(M(p.transpose().mmul(p)));
        final var rm = mm.inverse();
        println(rm.mmult(mm));
        
        var s = Arrays.asList(mm.getFlatCells2()).stream().map(e->e+"").collect(Collectors.joining(","));
        println(rm);
        println(MFT("mx<-matrix(c({0}),nrow={1})",s,n));
        println(mm);
        
    }
}
